package com.example.spring_source_code;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebServerApplicationContext {
    public static void main(String[] args) {

    }
    @Configuration
    static class Config{
        //创建web容器对象
        @Bean
        public ServletWebServerFactory serverFactory() {
            return new TomcatServletWebServerFactory();
        }
        //创建前置处理器
        @Bean
        public DispatcherServlet dispatcherServlet() {
            return new DispatcherServlet();
        }
        //前置处理器绑定到web容器
        @Bean
        @Primary
        public DispatcherServletRegistrationBean registrationBean(@Qualifier("dispatcherServlet") DispatcherServlet dispatcherServlet) {
            return new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        }

        @Bean("/hello")
        public Controller controller() {
            return (request, response) ->
            {
                response.getWriter().printf("hello");
                return null;
            };
        }

    }
}
